package com.yisu.auction.manager.core.service.impl;


import com.yisu.auction.ewf.common.enums.ResponseCode;
import com.yisu.auction.ewf.common.exception.StageException;
import com.yisu.auction.ewf.common.utils.QiNiuUploadUtil;
import com.yisu.auction.ewf.entity.Prize;
import com.yisu.auction.ewf.entity.PrizeArchive;
import com.yisu.auction.ewf.entity.Sms;
import com.yisu.auction.ewf.entity.SystemNotice;
import com.yisu.auction.manager.core.mapper.PrizeArchiveMapper;
import com.yisu.auction.manager.core.mapper.PrizeMapper;
import com.yisu.auction.manager.core.mapper.SmsMapper;
import com.yisu.auction.manager.core.mapper.SystemNoticeMapper;
import com.yisu.auction.manager.domain.config.SystemConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

/**
 * Created by zj on 2017/4/24.
 */
public class BaseService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    protected SystemConfig systemConfig;
    @Resource
    private PrizeMapper prizeMapper;
    @Resource
    private PrizeArchiveMapper prizeArchiveMapper;

    @Resource
    private SmsMapper smsMapper;
    @Resource
    private SystemNoticeMapper systemNoticeMapper;

    /**
     * 添加消息推送
     *
     * @param content  消息内容
     * @param mobile   手机号
     * @param sendType 发送类型
     * @param memberId 会员ID
     * @param prizeId  竞品ID
     * @param term     期号
     * @param sendTime 发送时间
     * @return
     */
    public boolean addSmsPush(String content, String mobile, byte sendType, long memberId, long prizeId, int term, Date sendTime) {
        Sms sms = new Sms();
        sms.setIsValid(true);
        sms.setContent(content);
        sms.setMobile(mobile);
        sms.setSendType(sendType);
        sms.setMemberId(memberId);
        sms.setPrizeId(prizeId);
        sms.setSendTime(sendTime);
        sms.setStatus((byte) 0);
        sms.setCreateDate(new Date());
        smsMapper.insertSelective(sms);
        return true;
    }

    /**
     * 添加消息推送
     *
     * @param content  消息内容
     * @return
     */
    public boolean addSystemNotice(String content, long toMemberId,String title,String contentAbstract,int msgType) {
        SystemNotice systemNotice= new SystemNotice();
        systemNotice.setContent(content);
        systemNotice.setToMemberId(toMemberId);
        systemNotice.setTitle(title);
        systemNotice.setContentAbstract(contentAbstract);
        systemNotice.setMsgType(msgType);
        systemNotice.setCreateDate(new Date());
        systemNoticeMapper.insertSelective(systemNotice);
        return true;
    }



    /**
     * 通过prizeId获取竞品
     *
     * @param prizeId 竞品Id
     * @return
     */
    public Prize getPrizeById(long prizeId) {
        Prize prize = prizeMapper.selectByPrimaryKey(prizeId);
        if (prize == null) {
            PrizeArchive prizeArchive = prizeArchiveMapper.selectByPrimaryKey(prizeId);
            if (prizeArchive != null)
                prize = new Prize(prizeArchive);
        }
        return prize;
    }



    protected boolean deleteFile(String fileName) {
        try {
            QiNiuUploadUtil.Uploader uploader = new QiNiuUploadUtil.Uploader();
            uploader.setAccessKey(systemConfig.getQiNiuAccessKey());
            uploader.setSecretKey(systemConfig.getQiNiuSecretKey());
            uploader.setBucketName(systemConfig.getQiNiuBucketName());
            uploader.setFileName(fileName);
            QiNiuUploadUtil.delete(uploader);
            return true;
        } catch (Exception e) {

        }
        return false;
    }


    protected String uploadFile(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String newFileName = QiNiuUploadUtil.generateFileName() + originalFileName.substring(originalFileName.lastIndexOf("."));

        QiNiuUploadUtil.Uploader uploader = new QiNiuUploadUtil.Uploader();
        uploader.setAccessKey(systemConfig.getQiNiuAccessKey());
        uploader.setSecretKey(systemConfig.getQiNiuSecretKey());
        uploader.setBucketName(systemConfig.getQiNiuBucketName());
        uploader.setFileName(newFileName);
        try {
            byte[] data = new byte[(int) file.getSize()];
            InputStream in = file.getInputStream();
            in.read(data);
            uploader.setData(data);
            if (QiNiuUploadUtil.upload(uploader)) {
                StringBuilder sb = new StringBuilder(80);
                sb.append(systemConfig.getQiNiuImageHost());
                if (!systemConfig.getQiNiuImageHost().endsWith("/")) {
                    sb.append("/");
                }
                sb.append(newFileName);
                return sb.toString();
            } else {
                throw new StageException(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
            }
        } catch (Exception e) {
            throw new StageException(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
        }
    }

    protected String uploadFileForLocation(File file) {
        String originalFileName = file.getName();
        String newFileName = QiNiuUploadUtil.generateFileName() + originalFileName.substring(originalFileName.lastIndexOf("."));
        QiNiuUploadUtil.Uploader uploader = new QiNiuUploadUtil.Uploader();
        uploader.setAccessKey(systemConfig.getQiNiuAccessKey());
        uploader.setSecretKey(systemConfig.getQiNiuSecretKey());
        uploader.setBucketName(systemConfig.getQiNiuBucketName());
        uploader.setFileName(newFileName);
        try {
            byte[] data = new byte[(int) file.length()];
            InputStream in = new FileInputStream(file.getAbsolutePath());
            in.read(data);
            uploader.setData(data);
            if (QiNiuUploadUtil.upload(uploader)) {
                StringBuilder sb = new StringBuilder(80);
                sb.append(systemConfig.getQiNiuImageHost());
                if (!systemConfig.getQiNiuImageHost().endsWith("/")) {
                    sb.append("/");
                }
                sb.append(newFileName);
                return sb.toString();
            } else {
                throw new StageException(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
            }
        } catch (Exception ex) {
            throw new StageException(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);
        }
    }
}
